# -*- coding: utf-8 -*-
import cgi 
import datetime 
import logging 
 
from google.appengine.ext import db
from google.appengine.ext import webapp 
from google.appengine.ext.webapp.util import run_wsgi_app 
from google.appengine.api import images
from google.appengine.api.images import Image, Error, LargeImageError
 
#logging.getLogger().setLevel(logging.DEBUG) 
 
 
class ImageFile(db.Model):
    pic = db.BlobProperty(required=True)
    # small = 0 (w:140,h:200),large = 1(actual)
    size = db.IntegerProperty(required=True)
    aid = db.StringProperty(required=True)
    date = db.DateTimeProperty(auto_now_add=True) 
 
class MainPage(webapp.RequestHandler): 
  def get(self): 
    allimagefile = ImageFile.all()
    #print allimagefile.count()
    self.response.out.write('<html><body>')
    if allimagefile.count() > 0 :
        for timagefile in allimagefile.filter('size =', 1).order('-date').fetch(30): 
          self.response.out.write("<div><img src='get?aid=%s&size=%s'></img></div>" % 
                                  (timagefile.aid, timagefile.size)) 

    self.response.out.write(""" 
          <form action="/post" enctype="multipart/form-data" method="post"> 

            <div><label>Avatar:</label></div> 
            <div><input type="file" name="pic"/></div>
            <input type="hidden" value="/" name="url">
            <input type="hidden" value="xxxxxxxxxxxxxxxxxxxxxx" name="aid">
            <div><input type="submit" value="Sign postImage"></div> 
          </form> 
        </body> 
      </html>""") 
 
class getImage (webapp.RequestHandler): 
  def get(self): 
    aid = self.request.get("aid")
    size = int(self.request.get("size", 1))
    
    timagefile = ImageFile.all()
    timagefile = timagefile.filter('aid = ', aid).filter('size =', size).order('-date')
   
    if timagefile.count():
        timagefile = timagefile.get()
        self.response.headers['Content-Type'] = "image/PNG" 
        self.response.out.write(timagefile.pic) 
    else:
        timagefile = ImageFile.all().filter('aid = ', "NOIMAGE").filter('size =', 1).get()
        self.response.headers['Content-Type'] = "image/PNG" 
        self.response.out.write(timagefile.pic)
    return
 
class postImage(webapp.RequestHandler): 
  def post(self): 
    #判断是否已经存在，也就是是否为编辑
    aid = self.request.get("aid")
    pic = self.request.get("pic",'')
    url = self.request.get("url")
    if pic == '' :
        self.response.out.write('''没有上传图像，请后退。
        后退后重新上传图像 或 跳过''')  
        return     
    if ImageFile.all().filter('aid = ', aid).count() > 0 :
        for timage in ImageFile.all().filter('aid = ', aid).fetch(4):
            timage.delete()
    # pic 是二进制文件流
    # picImage 是可识别图像文件
    try:
        picSmall = images.resize(pic, 140, 200, images.PNG) 
        
        timagefileLarge = ImageFile(pic = db.Blob(pic), size = 1,aid = aid )
        timagefileLarge.put()   
        
        timagefileSmall = ImageFile(pic = db.Blob(picSmall), size = 0, aid =aid )
        timagefileSmall.put() 
    except Exception:
        self.response.out.write('''图像过大或上传错误，请后退。 
        后退后重新上传图像 或 跳过''')
        return
    self.redirect(url) 
 
 
application = webapp.WSGIApplication([ 
  ('/', MainPage), 
  ('/get', getImage), 
  ('/post', postImage) 
], debug=False) 
 
 
def main(): 
  run_wsgi_app(application) 
 
 
if __name__ == '__main__': 
  main()
